package com.cc2019.buke.user.Activity.address;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cc2019.buke.R;
import com.cc2019.buke.user.tools.myDatabaseHelper;

public class AddAddressInfoActivity extends AppCompatActivity {
    private EditText name;
    private EditText phone;
    private EditText address;
    private Button sure;
    private myDatabaseHelper dbHelper;
    Intent oldData;
    private String oldNAME;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address_info);

        name=(EditText)findViewById(R.id.add_address_name);
        phone=(EditText)findViewById(R.id.add_address_phone);
        address=(EditText)findViewById(R.id.add_address_address);

        dbHelper = myDatabaseHelper.getInstance(this);

        oldData = getIntent();
        if (oldData.getStringExtra("haveData").equals("true")) {
            initInfo();//恢复旧数据
        }
        sure=(Button) findViewById(R.id.add_address_sure);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name_=name.getText().toString();
                String phone_=phone.getText().toString();
                String address_=address.getText().toString();

                if(!TextUtils.isEmpty(name_)&&!TextUtils.isEmpty(phone_)&&!TextUtils.isEmpty(address_)){
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    db.beginTransaction();//开启事务
                    db.execSQL("delete from address where name=?", new String[]{oldNAME});
                    db.execSQL("insert into address(name,phone,address) values(?,?,?)",new String[]{name_,phone_,address_});
                    db.setTransactionSuccessful();//事务执行成功
                    db.endTransaction();
                    Intent intent=new Intent(AddAddressInfoActivity.this, AddressActivity.class);
                    startActivity(intent);
                }else {
                    Toast.makeText(AddAddressInfoActivity.this,"姓名电话地址均不能为空！！",Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

    private void initInfo() {

        String oldName=oldData.getStringExtra("name");
        oldNAME=oldName;
        name.setText(oldName);
        String oldPhone=oldData.getStringExtra("phone");
        phone.setText(oldPhone);
        String oleAddress=oldData.getStringExtra("address");
        address.setText(oleAddress);
    }
}